package mc.support.taobao.api;

import com.taobao.api.TaobaoRequest;
import com.taobao.api.request.UsersGetRequest;
import com.taobao.api.response.UsersGetResponse;
import mc.support.taobao.api.fields.Fields;
import mc.support.taobao.api.fields.GetUsersFields;

import java.util.Set;

/**
 * Created with IntelliJ IDEA. <br/>
 * Author: Francis Yuen    <br/>
 * Date: 2014-11-10  <br/>
 */
public class GetUsersReq extends AbstractReq<GetUsersReq, UsersGetResponse> {

    //limited by taobao api
    private static final int MAX_NICK_NUM = 40;

    private String nick;
    private Set<String> nicks;
    private Fields fields;

    private static String convertToString( Set<String> set ) {
        StringBuilder s = new StringBuilder();

        int num = set.size();
        int i = 0;
        for ( String n : set ) {
            if ( i < num - 1 ) {
                s.append( n ).append( ',' );
            } else {
                s.append( n );
            }
            i++;
        }

        return s.toString();
    }

    @Override
    protected TaobaoRequest toRequest() {
        UsersGetRequest req = new UsersGetRequest();

        if ( null != nicks ) {
            if ( null != nick ) {
                nicks.add( nick );
            }
            if ( nicks.size() > MAX_NICK_NUM ) {
                throw new RuntimeException( "nick number more than " + MAX_NICK_NUM );
            }
            req.setNicks( convertToString( nicks ) );
        } else {
            if ( null != nick ) {
                req.setNicks( nick );
            }
        }

        if ( null != fields ) {
            req.setFields( fields.toString() );
        }
        return req;
    }

    public GetUsersReq fields( GetUsersFields fields ) {
        this.fields = fields;
        return this;
    }

    public GetUsersReq nicks( Set<String> nicks ) {
        this.nicks = nicks;
        return this;
    }

    public GetUsersReq nick( String nick ) {
        this.nick = nick;
        return this;
    }

}
